package util.http;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.impl.conn.SystemDefaultRoutePlanner;
import org.apache.http.protocol.HttpContext;

import java.net.ProxySelector;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.regex.Pattern;

/**
 * @Desciption: copy from dajia SystemDefaultRoutePlannerExt
 * @author: Anc
 * @date: 2022/7/01
 */
@Slf4j
public class SystemDefaultRoutePlannerExt extends SystemDefaultRoutePlanner {
    public SystemDefaultRoutePlannerExt(ProxySelector proxySelector) {
        super(proxySelector);
    }

    @Override
    protected HttpHost determineProxy(HttpHost target, HttpRequest request, HttpContext context) throws HttpException {
        URI uri;
        try {
            uri = new URI(target.toURI());
        } catch (URISyntaxException var13) {
            throw new HttpException("Cannot convert host to URI: " + target, var13);
        }

        String scheme = uri.getScheme();
        String host = uri.getHost();
        StringBuilder nonProxyHost = new StringBuilder("localhost|127.*|[::1]|0.0.0.0|[::0]");
        String jvmNonProxyHost;
        String[] proxyHosts;
        int proxyHostsLength;
        int index;
        String proxyHost;
        if (scheme != null && scheme.toLowerCase()
            .equals("http")) {
            jvmNonProxyHost = System.getProperty("http.nonProxyHosts");
            if (jvmNonProxyHost != null && jvmNonProxyHost.trim()
                .length() > 0) {
                proxyHosts = jvmNonProxyHost.split("[|]");
                proxyHostsLength = proxyHosts.length;

                for (index = 0; index < proxyHostsLength; ++index) {
                    proxyHost = proxyHosts[index];
                    nonProxyHost.append("|")
                        .append(proxyHost.replaceAll("^\\*", ".*"));
                }
            }
        }

        if (scheme != null && scheme.toLowerCase()
            .equals("https")) {
            jvmNonProxyHost = System.getProperty("https.nonProxyHosts");
            if (jvmNonProxyHost != null && jvmNonProxyHost.trim()
                .length() > 0) {
                proxyHosts = jvmNonProxyHost.split("[|]");
                proxyHostsLength = proxyHosts.length;

                for (index = 0; index < proxyHostsLength; ++index) {
                    proxyHost = proxyHosts[index];
                    nonProxyHost.append("|")
                        .append(proxyHost.replaceAll("^\\*", ".*"));
                }
            }
        }

        return Pattern.matches(nonProxyHost.toString(), host) ? null : super.determineProxy(target, request, context);
    }
}
